//引入express
const express = require('express')
//创建web服务器
const app = express()
//挂载静态资源
app.use(express.static('./dist'))
const http = require('http').createServer(app)
//引入socket.io,解决双全工通信
const { Server } = require('socket.io')
const io = new Server(http,{
	// cors: {
	// 	origin: "*",
	// 	methods:['GET','POST']
	// }
	cors:true
})

// 引入管理房间的类

const { Client, ManageMap } = require('./map.js')
const managemap = new ManageMap()

//建立通信通道
io.on('connection', (socket) => {
	socket.on('seekplayer',(id, name, camp)=> {
		let client = new Client(id, name, camp)
		// 获得房间号
		let mapID = managemap.put(client)
		socket.join(mapID)
		socket.emit('roomid', mapID)
	})
    // 服务端接收消息
	socket.on('eatpiece',(roomid, bpieceCode, pieceCode, x, y) => {
        // 服务端转发消息
		socket.to(roomid).emit('beatpiece', bpieceCode, pieceCode, x, y)
	});
	socket.on('movepiece',(roomid, pieceCode, x, y) => {
		socket.to(roomid).emit('bmovepiece', pieceCode, x, y)
	});
	// socket.emit('backinfor','我是服务端消息1') 
	// (data) =>{
	// console.log(data)
	// io.emit('backinfor','我是服务端消息')
});


//服务器中间件
app.use((req,res,next) =>{
	next()
})
 

//启动服务器
http.listen('5003',(err) =>{
	//服务器启动成功
	if(!err){
		console.log('MMapp服务器启动成功，地址为：http://localhost:5003')
	}
})